package cn.ut.pc.one.xkb.filter;

import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;


/**
 * token拦截器
 * 判断请求参数是否包含access-token
 * 可根据实际需求进行更改
 *
 * @author xiongkaibin
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {
    private static Logger log = LoggerFactory.getLogger(TokenFilter.class);

    /**
     * 执行过滤器中的业务逻辑
     * 对请求参数的access-token进行判断
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("==========================执行自定义token全局过滤器====================");
        // 获取请求参数中的access-token
        String token = exchange.getRequest().getQueryParams().getFirst("access-token");
        if (StringUtils.isEmpty(token)) {
            log.error("===================未登录======================");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);

            // 添加响应体未生效，待修改
            Publisher<? extends DataBuffer> publisher = Flux.just(exchange.getResponse().bufferFactory().wrap("token is empty".getBytes()));
            exchange.getResponse().writeWith(publisher);

            // 请求结束
            return exchange.getResponse().setComplete();
        }
        // 存在token继续执行逻辑
        return chain.filter(exchange);
    }

    /**
     * 指定过滤器的执行顺序
     * 数值越小，执行优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
